package com.songcha.library_common.util

import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream

class FileUtil {
    companion object{
        @JvmStatic
        open fun deleteFileOrDirectory(file: File?): Boolean {
            try {
                if (file != null && file.isFile) {
                    return file.delete()
                }
                if (file != null && file.isDirectory) {
                    val childFiles = file.listFiles()
                    if (childFiles == null || childFiles.size == 0) {
                        return file.delete()
                    }
                    for (i in childFiles.indices) {
                        deleteFileOrDirectory(childFiles[i])
                    }
                    return file.delete()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return false
        }

        @JvmStatic
        public fun saveBitmap(context: Context, bitmap: Bitmap,savePath:String,saveName:String):Boolean {
            if (bitmap == null) {
                return false
            }
            var isSaveSuccess = false
            if (Build.VERSION.SDK_INT < 29) {
                isSaveSuccess = saveImageToGallery(context, bitmap,savePath,saveName)
            } else {
                isSaveSuccess = saveImageToGalleryQ(context, bitmap,saveName)
            }
            return isSaveSuccess
        }

        /**
         * below android 10
         */
        @JvmStatic
        private fun saveImageToGallery(context: Context, bitmap: Bitmap,savePath:String,saveName:String):Boolean {
            val appDir = File(savePath)
            if (!appDir.exists()) {
                appDir.mkdir()
            }
            val file = File(appDir, saveName)
            try {
                val fos = FileOutputStream(file)
                val isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
                fos.flush()
                fos.close()

                val uri = Uri.fromFile(file)
                context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri))
                return isSuccess
            } catch (e:IOException) {
                e.printStackTrace()
            }
            return false
        }

        @JvmStatic
        fun saveImage(context: Context, bitmap: Bitmap,path:String,name:String):Boolean {
            var file = File(path)
            if(!file.exists()){
                file.mkdir()
            }
            file = File(path + name)
            try {
                val fos = FileOutputStream(file)
                val isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
                fos.flush()
                fos.close()

                val uri = Uri.fromFile(file)
                context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri))
                return isSuccess
            } catch (e:IOException) {
                e.printStackTrace()
            }
            return false
        }

        /**
         * above android 10
         */
        private fun saveImageToGalleryQ(context: Context, bitmap: Bitmap,saveName:String):Boolean {
            val mImageTime = System.currentTimeMillis()

            val values = ContentValues()
            values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM)
            values.put(MediaStore.MediaColumns.DISPLAY_NAME, saveName)
            values.put(MediaStore.MediaColumns.MIME_TYPE, "image/png")
            values.put(MediaStore.MediaColumns.DATE_ADDED, mImageTime / 1000)
            values.put(MediaStore.MediaColumns.DATE_MODIFIED, mImageTime / 1000)
            values.put(MediaStore.MediaColumns.DATE_EXPIRES, (mImageTime + 3600 * 24 * 1000) / 1000)
            values.put(MediaStore.MediaColumns.IS_PENDING, 1)

            val resolver = context.contentResolver
            val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) ?: return false
            try {
                val out = resolver.openOutputStream(uri) ?: return false
                if (!bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
                    return false
                }
                values.clear()
                values.put(MediaStore.MediaColumns.IS_PENDING, 0)
                values.putNull(MediaStore.MediaColumns.DATE_EXPIRES)
                resolver.update(uri, values, null, null)
            } catch (e: Exception) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    resolver.delete(uri, null)
                }
                return false
            }
            return true
        }

    }
}